package org.znxs.comfriend.adapters;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.znxs.comfriend.R;
import org.znxs.comfriend.activities.ImageDetailActivity;

import java.util.List;

public class ImagePreviewAdapter extends RecyclerView.Adapter<ImagePreviewAdapter.ImageViewHolder> {

    private Context context;
    private List<String> imageUrls;
    private int screenWidth;

    public ImagePreviewAdapter(Context context, List<String> imageUrls, int screenWidth) {
        this.context = context;
        this.imageUrls = imageUrls;
        this.screenWidth = screenWidth;
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_image_preview, parent, false);
        return new ImageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        String imageUrl = imageUrls.get(position);

        // 动态设置 ImageView 的宽度和高度
        ViewGroup.LayoutParams layoutParams = holder.imageView.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = screenWidth; // 屏幕宽度
            layoutParams.height = (int) (screenWidth * 0.75); // 根据宽高比设置高度
            holder.imageView.setLayoutParams(layoutParams);
        }

        // 使用 Glide 加载图片
        Glide.with(context)
                .load(imageUrl)
                .placeholder(R.drawable.pengyiyan)
                .error(R.drawable.error)
                .into(holder.imageView);

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            // 启动 ImageDetailActivity 并传递图片 URL
            Intent intent = new Intent(context, ImageDetailActivity.class);
            intent.putExtra("image_url", imageUrl);
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return imageUrls == null ? 0 : imageUrls.size();
    }

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image_view_item);
        }
    }
}